package lbs.locationretreival;

/**
 * @author cris
 *
 */

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;	// provides location services
import android.location.LocationListener;	// // listens for change in location

import android.location.Address;
import android.location.Geocoder;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.MyLocationOverlay;
import android.graphics.drawable.Drawable;

/*
 * Class to retreive the best estimate of user's location and updates location on
 * change every MIN_TIME_FOR_UPDATE or _MIN_DISTANCE_FOR UPDATE.
 * 
 */
public class LocationGetterActivity extends MapActivity {
	 
	/** Called when the activity is first created. */
	
		private LocationManager l_manager;
		private TextView view;
		private Location location;
		private String l_provider;	// location provider
		private Criteria criteria;
		public static Context context;
	//	private final LocationListener listener;
		private MapView map;
		private List<Overlay> overlays;
		private MarkerOverlay marker_layer;
		private MapController m_controller;
		
		private static final long MIN_TIME_FOR_UPDATE =  2000;	//milliseconds
		private static final int MIN_DISTANCE_FOR_UPDATE =  2;	//meters
		
		/* define accurancy and power requirements for location gathering */
		private static final int ACCURACY = Criteria.ACCURACY_FINE;
		private static final int POWER = Criteria.POWER_LOW;
		
		
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	    	
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        context = this;
	        view = (TextView) findViewById(R.id.view1);		// text area in ui
	        map = (MapView) findViewById(R.id.map1);		// map area
	        l_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	             
	        criteria = new Criteria();
	        set_criteria(ACCURACY, POWER);
	           
	        //location provider could be gps or network based on criteria
	        l_provider = l_manager.getBestProvider(criteria, true);
	        
	        //-----------map stuff--------------
	        overlays = map.getOverlays();
	        Drawable drawable = this.getResources().getDrawable(R.drawable.my_icon);
	        marker_layer = new MarkerOverlay(drawable);
	        
	        
	        location = l_manager.getLastKnownLocation(l_provider);
	        l_manager.requestLocationUpdates(l_provider, MIN_TIME_FOR_UPDATE, 
	        		MIN_DISTANCE_FOR_UPDATE, listener);
	        
	        //co-ordinates for marker on map
	        int geo_lat = (int) (location.getLatitude() * 1E6);
	        int geo_long = (int) (location.getLongitude() * 1E6); 
	        
	        
	        /*	create point and go to it on map
	         * add it to overlay items (calls populate function)
	         */
	        map.setBuiltInZoomControls(true);
	        GeoPoint point = new GeoPoint(geo_lat, geo_long);
	        m_controller = map.getController();
	        m_controller.animateTo(point);
	        m_controller.setZoom(3);
	        
	        OverlayItem overlayitem =
	        		new OverlayItem(point, "SSID: TCDwifi", " etc...");
	        		// can use reverse geocoding to get address
	        
	        marker_layer.addOverlayItem(overlayitem);
	        overlays.add(marker_layer);
	        	        
    		view.setText("GeoPoint point: \ngeo_lat:" + geo_lat +
    				"\ngeo_long: " + geo_long + '\n' );
    		
    	   		
	  //      showlocation();
	        	        	        
	    }
	    
	    /* tidier-upper method */
	    private void set_criteria(final int accurracy, final int power){
	        criteria.setAccuracy(accurracy);
	        criteria.setPowerRequirement(power);
	    }
	    
	    /* display location on screen */
		private void showlocation() {
			view.append("\nLast known location: \t\nlat: " + location.getLatitude()
		       		+ " \t\nlong: " + location.getLongitude());
		}
	    
		
		
		// declare the location listener and override its methods
		// this is an alternative to implementing locationlistener within activity
		// Might take this out to tidy up
		public final LocationListener listener = new LocationListener(){
			
			
			@Override
			/* Update location variable and display update location in text view*/
			public void onLocationChanged(Location new_location) {
				// TODO Auto-generated method stub
				//Don't do a lot of processing in here, will reduce performance.
				location = new_location;
				showlocation();
			}
	
		
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
	
	
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
	
	
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
	    };

		public boolean onCreateOptionsMenu(Menu menu)
		{
			MenuInflater mi = getMenuInflater();
			mi.inflate(R.menu.options, menu);
			return true;
		}
		
		public boolean onOptionsItemSelected(MenuItem item)
		{
			switch (item.getItemId())
			{
					
				case R.menu_id.EXIT:
					finish();
					break;
					
	            case R.menu_id.LIST:            
	            	Intent i = new Intent(this, DataLoggerActivity.class);
	                startActivity(i);
	                break;

			}
			
			return true;
		}

	    
	    //map
		@Override
		protected boolean isRouteDisplayed() {
			// TODO Auto-generated method stub
			return false;
		}
}

